package com.example.netchat;

import static com.example.netchat.CommonUtilities.SENDER_ID;

import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {
	public GCMIntentService() {
		super(SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		String oldRegId = PreferenceManager
				.getDefaultSharedPreferences(context).getString(
						CommonUtilities.REG_PREF, null);

		Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
				.edit();

		editor.putString(CommonUtilities.REG_PREF, registrationId);
		editor.commit();

		context.startService(ChatService.createJoinAllRoomsIntent(context,
				oldRegId));
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
				.edit();

		editor.remove(CommonUtilities.REG_PREF);
		editor.commit();
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Bundle extras = intent.getExtras();
		String from = extras.getString("message_from");
		String message = extras.getString("content");
		String roomId = extras.getString("room_id");

		context.startService(ChatService.createMessageArrivedIntent(context,
				roomId, from, message, new Date()));
	}
	
	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return super.onRecoverableError(context, errorId);
	}
	
	@Override
	protected void onDeletedMessages(Context context, int total) {
		super.onDeletedMessages(context, total);
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Device registration error: errorId = " + errorId);
	}
}